package com.chushouya.manager.service.websocket;

import com.chushouya.manager.dto.admin.im.Content;
import com.chushouya.manager.dto.admin.im.Event;
import com.chushouya.manager.dto.admin.im.Message;
import com.general.framework.core.lang.IdTakes;
import com.general.framework.core.lang.Jsons;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;


@Component
@Slf4j
@ServerEndpoint(value = "/websocket/{clientId}")
public class IMWebSocketServer {

    public static Map<String, Session> SESSION_MAPS = new ConcurrentHashMap<>();

    private static final String IM_SERVER = "im-server";

    private static final String PING = "0x9";

    private static final String PONG = "0xA";

    @PostConstruct
    public void init() {
        log.info("webSocket init");
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("clientId") String clientId) {
        Message message = new Message();
        message.setFrom(IM_SERVER);
        message.setTo(clientId);
        message.setEvent(Event.connectionSuccess.value());
        SESSION_MAPS.put(clientId, session);
        log.info("===>有连接加入,sessionId:{}, clientId:{},当前连接数为:{}", session.getId(), clientId, SESSION_MAPS.size());
        sendMessage(session, message);
    }



    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("clientId") String clientId) {
        SESSION_MAPS.remove(clientId);
        log.info("===>有连接关闭,sessionId:{}, clientId:{},当前连接数为:{}", session.getId(), clientId, SESSION_MAPS.size());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param data 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String data, Session session, @PathParam("clientId") String clientId) {
        if (Objects.equals(PING, data)) {
            try {
                session.getBasicRemote().sendText(PONG);
                return;
            } catch (Exception e) {
                log.error("send pong error");
                return;
            }
        }
        log.info("===>收到消息,sessionId:{}, clientId:{}, data:{}", session.getId(), clientId, data);
        Message message = new Message();
        message.setFrom(IM_SERVER);
        message.setTo(clientId);
        message.setEvent(Event.receiveSuccess.value());
        Content content = new Content();
        content.setBizId(IdTakes.takeRandomNum(10));
        content.setData(Event.receiveSuccess.named().concat(data));
        message.setContent(content);
        sendMessage(session, message);
    }

    /**
     * 发生错误
     */
    @OnError
    public void onError(Session session, @PathParam("clientId") String clientId, Throwable e) {
        log.error("===>发生错误,sessionId:{}, clientId:{}", session.getId(), clientId, e);
    }

    /**
     * 发送消息
     */
    private static boolean sendMessage(Session session, Message message) {
        try {
            if (Objects.nonNull(session) && session.isOpen()) {
                session.getBasicRemote().sendText(Jsons.toJsonString(message));
                return true;
            }else {
                asyncSaveMessage(message);
            }
        } catch (IOException e) {
            log.error("发送消息出错", e);
            asyncSaveMessage(message);
        }
        return false;
    }

    /**
     * 异步保存消息
     */
    private static void asyncSaveMessage(Message message){
        //log.debug("===>推送给{}失败,异步保存消息:{}", message.getTo(), Jsons.toJsonString(message));
    }

    /**
     * 发送消息
     */
    public static void sendOne(Message message) {
       sendMessage(SESSION_MAPS.get(message.getTo()), message);
    }

    /**
     * 群发消息
     */
    public static void broadCast(Content content) {
        Message message = new Message();
        message.setFrom(IM_SERVER);
        message.setEvent(Event.messagePush.value());
        message.setContent(content);
        message.setEvent(Event.messagePush.value());
        for (String clientId : SESSION_MAPS.keySet()) {
            message.setTo(clientId);
            sendMessage(SESSION_MAPS.get(clientId), message);
        }
    }

    /**
     * 群发消息
     */
    public static void broadCast(Content content, String prefix, List<Long> idList) {
        Message message = new Message();
        message.setFrom(IM_SERVER);
        message.setEvent(Event.messagePush.value());
        message.setContent(content);
        idList.forEach(id->{
            final String clientId = prefix + id;
            message.setTo(clientId);
            sendMessage(SESSION_MAPS.get(clientId), message);
        });
    }

    /**
     * 群发消息
     */
    public static void broadDataCast(Content content, String prefix, List<Long> idList) {
        Message message = new Message();
        message.setFrom(IM_SERVER);
        message.setEvent(Event.dataPush.value());
        message.setContent(content);
        idList.forEach(id->{
            final String clientId = prefix + id;
            message.setTo(clientId);
            sendMessage(SESSION_MAPS.get(clientId), message);
        });
    }

    /**
     * 服务端请求断开某个连接
     * @param clientId clientId
     */
    public static void requestClose(String clientId) {
        Message message = new Message();
        message.setFrom(IM_SERVER);
        message.setTo(clientId);
        message.setEvent(Event.requestClose.value());
        sendMessage(SESSION_MAPS.get(clientId), message);
    }

}
